﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace WPControls
{
    /// <summary>
    /// Convert(str, idx) returns str.split(' ')[idx]
    /// </summary>
    public class StringSplitConverter : IValueConverter
    {
        /// <summary>
        /// Converts.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns>value.split(' ')[(int)parameter]</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                int num = 0;
                if (value is string && (parameter is int || int.TryParse((string)parameter, out num)))
                {
                    string[] parts = (value as string).Split(' ');

                    int idx = parameter is int ? (int)parameter : num;
                    
                    if (idx < parts.Length)
                        return parts[num];
                }
            }
            catch
            {
                return value;
            }

            return null;
        }

        /// <summary>
        /// Returns null.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
